package com.gx.util.dbutil;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 获取数据库连接池
 * Created by gx on 2017/7/7.
 */
public class DbPoolConnection {
    private static final Logger log = LoggerFactory.getLogger(DbPoolConnection.class);
    private static DbPoolConnection databasePool = null;
    private static DruidDataSource dds = null;

    private DbPoolConnection() {
        String fileName ="config/db_server.properties";
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(DbPoolConnection.class.getClassLoader().
                    getResourceAsStream(fileName),"UTF-8"));
            dds = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(properties);
        } catch (IOException e) {
            log.error("创建druid数据源失败原因:{} errr:{}","读取配置文件失败",e.getMessage(),e);
        } catch (Exception e) {
            log.error("创建druid数据源失败原因:{} errr:{}","报错",e.getMessage(),e);
        }

    }

    public DbPoolConnection(String fileName) {
//        String fileName ="db_server.properties";
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(DbPoolConnection.class.getClassLoader().
                    getResourceAsStream(fileName),"UTF-8"));
            dds = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(properties);
        } catch (IOException e) {
            log.error("创建druid数据源失败原因:{} errr:{}","读取配置文件失败",e.getMessage(),e);
        } catch (Exception e) {
            log.error("创建druid数据源失败原因:{} errr:{}","报错",e.getMessage(),e);
        }

    }

    //加载配置文件获得 DataSource
//    static {
//    }


    //获取DbPoolConnection
    public static DbPoolConnection getInstance() {
        if (null == databasePool) {
            synchronized (DbPoolConnection.class) {
                if (null == databasePool) {
                    databasePool = new DbPoolConnection();
                }
            }
        }
        return databasePool;
    }
    public static DbPoolConnection getInstance(String filename) {
        if (null == databasePool) {
            synchronized (DbPoolConnection.class) {
                if (null == databasePool) {
                    databasePool = new DbPoolConnection(filename);
                }
            }
        }
        return databasePool;
    }
    // 获得数据源
    public DruidDataSource getDataSource() throws SQLException {
        return dds;
    }

//    获取连接池
    public DruidPooledConnection getConnection() throws SQLException {
        return dds.getConnection();
    }


}
